<?php
namespace App\Http\Controllers\Alipay;
use Alipay\EasySDK\Kernel\Factory;
use App\Jobs\Recharge;
use App\Jobs\RechargeApi;
use App\Jobs\SyncRecharge;
use App\Models\NsSupplierGoods;
use App\Models\NsSupplierGoodsCoupon;
use App\Models\XnH5Order;
use App\Models\XnMerchant;
use App\Models\XnMyyGoodsInterconnection;
use App\Recharge\Library;
use App\Services\AlipayService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class AlipayController
{
    public function alipayNotify(Request $request)
    {
        $params = $request->all();
        Log::channel('alipayResult') -> info('支付异步回调结果：', $params);
        // 验证签名
        $service = new AlipayService();
        $service ->validateSign($params);
        // 处理业务逻辑
        if ($params['trade_status'] === 'TRADE_SUCCESS') {
            $orderInfo = Redis::get('h5_'.$params['out_trade_no']);
            if(!$orderInfo){
                Log::channel('alipayResult') -> info('订单信息',json_decode($orderInfo,true));
                return response('订单信息找不到', 400);
            }
            parse_str($params['passback_params'],$output);
            $output['alipay_order'] = $params['trade_no'];
            $gidInfo = XnMyyGoodsInterconnection::query() -> where('id',$output['gid']) -> value('merchant');
            if(!$gidInfo){
                Log::channel('alipayResult') -> info('商品信息未找到：',$output);
                return response('商品信息未找到', 400);
            }
            $secret = XnMerchant::query() -> where('Merchant_number',$gidInfo) -> value('secret_key');
            if(!$secret){
                Log::channel('alipayResult') -> info('商户信息未找到',$output);
                return response('未查询到商户信息', 400);
            }
            $output['secret'] = $secret;
            SyncRecharge::dispatch($output)->onQueue('h5_order_job');
            //$this -> createPlatformOrder($output);
        }
        return response('success'); // 必须返回纯文本 success
    }

    public function alipayCouponNotify(Request $request)
    {
        $params = $request->all();
        Log::channel('alipayResult') -> info('支付（优惠券）异步回调结果：', $params);
        // 验证签名
        $service = new AlipayService();
        $service ->validateSign($params);
        // 处理业务逻辑
        if ($params['trade_status'] === 'TRADE_SUCCESS') {
            $orderInfo = Redis::get('h5_coupon_'.$params['out_trade_no']);
            if(!$orderInfo){
                Log::channel('alipayResult') -> info('支付（优惠券）订单信息',json_decode($orderInfo,true));
                return response('订单信息找不到', 400);
            }
            parse_str($params['passback_params'],$output);
            $output['alipay_order'] = $params['trade_no'];
            $secret = XnMerchant::query() -> where('Merchant_number',$output['merchant']) -> value('secret_key');
            if(!$secret){
                Log::channel('alipayResult') -> info('支付（优惠券）商户信息未找到',$output);
                return response('未查询到商户信息', 400);
            }
            $output['secret'] = $secret;
            RechargeApi::dispatch($output)->onQueue('h5_coupon_recharge_job');
        }
        return response('success'); // 必须返回纯文本 success
    }

    public function alipaySync(Request $request)
    {
        $params = $request->all();
        $result = Factory::payment()->common()->verifyNotify($params);

        if ($result) {
            // 跳转到支付成功页面
            return view('pay.success');
        } else {
            return view('pay.error');
        }
    }

    public function createh5Pay(Request $request){
        $gid = $request -> post('gid');
        if(empty($gid)){
            return fails('缺少参数');
        }
        $account = auth('interface') -> user() -> phone;
        Log::channel('alipayResult') -> info('充值账号',['account'=>$account]);
        $goods_info = XnMyyGoodsInterconnection::query()
            -> where('id','=',$gid)
            -> where('status',1)
            -> first();
        if(!$goods_info){
            return fails('商品信息未查询到');
        }
        $order = [
            'out_trade_no' => Library::order_no(),
            'total_amount' => $goods_info -> price,
            'subject' => urlencode(mb_convert_encoding('下单'.$goods_info -> g_name.'商品', 'GB2312' ))
        ];
        $passBackArr = [
            'gid'=>$gid,
            'account'=>$account,
            'money'=>$goods_info -> price ,
            'order_no'=>$order['out_trade_no'],
            'num'=>1
        ];
        Redis::setex('h5_'.$order['out_trade_no'], 1200, json_encode($passBackArr));
        $passBack = urlencode(http_build_query($passBackArr));
        Log::channel('alipayResult') -> info('订单信息',$order);
        $alipay = new AlipayService();
        $response = $alipay->h5Pay($order['out_trade_no'],$order['total_amount'],$order['subject'],$passBack);
        return successly($response->body);
    }

    public function createH5CouponPay(Request $request){
        $gid = $request -> post('gid');
        if(empty($gid)){
            return fails('缺少参数');
        }
        $account = $request -> post('account');
        if(empty($account)){
            return fails('缺少参数');
        }
        $goods_info = NsSupplierGoods::query()
            -> where('id','=',$gid)
            -> select('id','is_up','release','price','profit','h5_show','goodsName')
            -> firstOrFail();
        if($goods_info ->h5_show != 3){
            return fails('商品状态异常_h5');
        }
        if($goods_info ->is_up != 1){
            return fails('商品状态异常_up');
        }
        if($goods_info ->release != 1){
            return fails('商品状态异常_release');
        }
        $coupon = $request -> post('coupon','');
        $amount = $this -> calculatePaymentAmount($goods_info,$coupon);
        $orderNo = Library::order_no();
        $order = [
            'out_trade_no' => $orderNo,
            'total_amount' => $amount,
            'subject' => urlencode(mb_convert_encoding('下单'.$goods_info -> goodsName.'商品', 'GB2312' ))
        ];
        $passBackArr = [
            'gid' => $gid,
            'account' => $account,
            'money' => $amount,
            'order_no' => $orderNo,
            'coupon' =>$coupon,
            'merchant' =>'1246748956',
            'num' => 1
        ];
        XnH5Order::query() -> insert([
            'user'=>auth('h5user') ->user()-> id,
            'gid'=>$gid,
            'goods_name'=>$goods_info->goodsName,
            'order_sn'=>$orderNo,
            'account'=>$account,
            'coupon'=>$coupon,
            'created_at'=>now()
        ]);
        Redis::setex('h5_coupon_'.$order['out_trade_no'], 1200, json_encode($passBackArr));
        $passBack = urlencode(http_build_query($passBackArr));
        Log::channel('alipayResult') -> info('订单信息',$order);
        $alipay = new AlipayService(AlipayService::NOTIFY_ALTERNATE);
        $response = $alipay->h5Pay($order['out_trade_no'],$order['total_amount'],$order['subject'],$passBack);
        return successly($response->body);
    }
    private function calculatePaymentAmount(NsSupplierGoods $good, string $coupon = ''): float
    {
        $amount = $good->price + $good->profit;

        if (!$coupon) return round($amount, 2);

        $couponInfo = NsSupplierGoodsCoupon::query()->where('coupon', $coupon)
            ->where('state', 2)
            ->firstOrFail();

        if ($amount <= $couponInfo->price) {
            throw new \Exception('优惠券金额不能大于等于商品价格');
        }

        return round($amount - $couponInfo->price, 2);
    }
    public function testOrder(Request $request){
        $orderInfo = [
            'gid'=>$request->post('gid'),
            'account'=>$request->post('account'),
            'order_no'=>$request->post('order_no'),
            'num'=>$request->post('num'),
            'money'=>$request->post('money'),
            'alipay_order'=>$request->post('alipay_order'),
        ];
        $time = Carbon::now();
        $good = XnMyyGoodsInterconnection::query() -> where('id',$orderInfo['gid']) -> first();
        $order = [
            'gid'                   => 1,
            'goodsId'               => $good->id,
            'userName'              => $orderInfo['account'],
            'productType'           => 0,
            'orderNum'              => $orderInfo['order_no'],
            'price'                 => $good->price,
            'unitPrice'             => $good->unit_price,
            'rechargeNum'           => $orderInfo['num'],
            'rechargeMoney'         => $orderInfo['money'],
            'recharge_time'         => $time,
            'recharge_status'       => 0,
            'place_order_people'    => 'H5联合商品下单',
            'goodsName'             => $good->g_name,
            'merchantOrderNum'      => $orderInfo['alipay_order'],
            'business'              => 19,  //h5联合商品下单
            'Merchant_number'       => $good->merchant,
            'myy_h5_type'           => 2,
        ];
        // 账单
        $order_bill = [
            'supplier_id'       => 1,
            'goods_explain'     => $good->g_name . '商品',
            'bookkeeping_type'  => 1,
            'order_num'         => $order['orderNum'],
            'account'           => $order['userName'],
            'price'             => $good->price,
            'goods_num'         => $order['rechargeNum'],
            'business_type'     => $order['business'],
            'budget_money'      => $order['rechargeMoney'],
            'ctime'             => date('Y-m-d H:i:s'),
            'goods_id'          => $good->id,
            'brand_id'          => $good->brand_id,
            'merchant_name'     => $order['place_order_people'],
            'refund_time'       => '1970-01-01 08:00:00'
        ];
        $Merchant_info = XnMerchant::query()->where('Merchant_number',$good->merchant)->first();
        $merchant_bill = [
            'merchant_number'=>$good->merchant,
            'time'=>date('Y-m-d H:i:s',time()),
            'status'=>2,
            'before_transaction_balance'=>$Merchant_info['balance'],
            'transaction_amount'=>$order['rechargeMoney'],
            'after_transaction_balance'=>($Merchant_info['balance']-$order['rechargeMoney']),
            'merchant_order'=>$order['orderNum'],
            'trading_status'=>5,
        ];
       // Redis::del('h5_'. $orderInfo['order_no']);
        Recharge::dispatch( $order, $merchant_bill, $order_bill, $good, '')->onQueue('h5_order_job');
    }
    // 创建接口订单下单
    public function createPlatformOrder($orderInfo){
        $time = Carbon::now();
        $good = XnMyyGoodsInterconnection::query() -> where('id',$orderInfo['gid']) -> first();
        $order = [
            'gid'                   => 1,
            'goodsId'               => $good->id,
            'userName'              => $orderInfo['account'],
            'productType'           => 0,
            'orderNum'              => $orderInfo['order_no'],
            'price'                 => $good->price,
            'unitPrice'             => $good->unit_price,
            'rechargeNum'           => $orderInfo['num'],
            'rechargeMoney'         => $orderInfo['money'],
            'recharge_time'         => $time,
            'recharge_status'       => 0,
            'place_order_people'    => 'H5联合商品下单',
            'goodsName'             => $good->g_name,
            'merchantOrderNum'      => $orderInfo['alipay_order'],
            'business'              => 19,  //h5联合商品下单
            'Merchant_number'       => $good->merchant,
            'myy_h5_type'           => 2,
        ];
        // 账单
        $order_bill = [
            'supplier_id'       => 1,
            'goods_explain'     => $good->g_name . '商品',
            'bookkeeping_type'  => 1,
            'order_num'         => $order['orderNum'],
            'account'           => $order['userName'],
            'price'             => $good->price,
            'goods_num'         => $order['rechargeNum'],
            'business_type'     => $order['business'],
            'budget_money'      => $order['rechargeMoney'],
            'ctime'             => date('Y-m-d H:i:s'),
            'goods_id'          => $good->id,
            'brand_id'          => $good->brand_id,
            'merchant_name'     => $order['place_order_people'],
            'refund_time'       => '1970-01-01 08:00:00'
        ];
        $Merchant_info = XnMerchant::query()->where('Merchant_number',$good->merchant)->first();
        $merchant_bill = [
            'merchant_number'=>$good->merchant,
            'time'=>date('Y-m-d H:i:s',time()),
            'status'=>2,
            'before_transaction_balance'=>$Merchant_info['balance'],
            'transaction_amount'=>$order['rechargeMoney'],
            'after_transaction_balance'=>($Merchant_info['balance']-$order['rechargeMoney']),
            'merchant_order'=>$order['orderNum'],
            'trading_status'=>5,
        ];
        Redis::del('h5_'. $orderInfo['order_no']);
        Recharge::dispatch( $order,$merchant_bill, $order_bill, $good, '')->onQueue('h5_order_job');
    }
}
